/**
 * @Description:功能角色页面
 * @Author: CHEHSHUANG
 * @Date: 2019/1/24
 */
import React, {Component} from 'react';
import {Button, Col, message, Row, Modal,Input} from "antd";
import SimpleTable from "../../../commons/components/SimpleTable";
import {
  deleteRole,
  deleteRoleGroup,
  findFeatureRoleByGroupId,
  findFeatureRoleGroup,
  getPosition,
  getUser,
  saveFeatureRole,
  saveFeatureRoleGroup
} from "./FeatureRoleService";
import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import {cache, searchListByKey, searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import EditRoleGroupModal from "./EditRoleGroupModal";
import EditRoleModal from "./EditRoleModal";
import ShowConfigPage from "./ShowConfigPage";
import DetailCard from "../../../commons/components/DetailCard";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import {rowGutter} from "../../../configs/DefaultConfig";
import StandardDropdown from "../../../commons/components/StandardDropdown";
import ModalBox from "./ModalBox";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";
import ToolBar from "../../../commons/components/toolbar/ToolBar";
import AddOrEditRoleModal from "./AddOrEditRoleModal";

const confirm = Modal.confirm;
const Search = Input.Search;

class FeatureRoleView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "功能角色管理"}];
    this.state = {
      roleGroupDataSource: [],//功能角色组
      roleDataSource: [],//功能角色
      searchGroupValue: "",//功能角色组查询关键字
      searchRoleValue: "",//功能角色查询关键字
      groupSelectedRows: [],//功能角色组选中的行,
      roleSelectedRows: [],
      roleVisible: false,
      groupVisible: false,
      isRoleEdit: false,
      isGroupEdit: false,
      confirmLoading: false,
      groupEditData: null,
      roleEditData: null,
      showUser: false,
      showPosition: false,
      showConfigPage: false,
    }
  }


  componentDidMount() {
    this.getDataSource();
  }

  getGroupFormRef = (ref) => {
    this.groupFormRef = ref;
  }
  getRoleFormRef = (ref) => {
    this.roleFormRef = ref;
  }
  getDataSource = (searchGroupValue) => {
    this.props.show();
    findFeatureRoleGroup().then(res => {
      searchListByKeyWithTag(res, {keyword: searchGroupValue}, ['code', 'name']).then(searchData => {
        this.setState({roleGroupDataSource: searchData})
      })
    }).catch(e => {
    }).finally(() => {
      this.props.hide();
    })
  }
  getRoleDataByGroup = (groupId,searchRoleValue) => {
    if (!groupId) {
      return false;
    }
    this.props.show();
    findFeatureRoleByGroupId(groupId).then((res) => {
      searchListByKeyWithTag(res, {keyword: searchRoleValue}, ['code', 'name']).then(searchData => {
        this.setState({roleDataSource: searchData});
      })

    }).catch(e => {
    }).finally(() => {
      this.props.hide();
    })
  }
  handleQuickSearchGroup = (searchValue) => {
    searchListByKeyWithTag(this.state.roleGroupDataSource, {keyword: searchValue}, ['code', 'name']).then(searchData => {
      this.setState({roleGroupDataSource:searchData, searchGroupValue: searchValue})
    })
  }
  handleQuickSearchRole = (searchValue) => {
    searchListByKeyWithTag(this.state.roleDataSource, {keyword: searchValue}, ['code', 'name']).then(searchData => {
      this.setState({roleDataSource: searchData, searchRoleValue: searchValue})
    })
  }
  handleAddGroup = (e) => {
    this.setGroupModalVisible(true);
  }
  handleEditGroup = (groupEditData) => {
    if (groupEditData) {
      this.setState({groupEditData});
      this.setGroupModalVisible(true, true);
    } else {
      message.error("数据不存在");
    }
  }
  handleDeleteGroup = (groupEditData) => {
    let thiz=this;
    if (groupEditData) {
      this.setState({groupEditData});
      let id = groupEditData.id;
      confirm({
        title: "温馨提示",
        content: "删除后不可恢复，是否确定删除？",
        onOk: () => {
          thiz.props.show();
          deleteRoleGroup(id).then((res) => {
            if (res.status.toLowerCase() === "success") {
              message.success(res.message || "删除成功");
            } else {
              message.error(res.message);
            }
            thiz.setGroupModalVisible(false);
            thiz.getDataSource(thiz.state.searchGroupValue);
          }).catch(e => {
            message.error('删除失败');
          }).finally(() => {
            thiz.props.hide();
          })
        }
      });
    } else {
      message.error("数据不存在");
    }
  }
  handleAddRole = () => {
    if (this.state.groupSelectedRows.length !== 0) {
      this.setRoleModalVisible(true);
    } else {
      message.error("请选择一个功能角色组");
      return false;
    }
  }

  handleEditRole = (roleEditData) => {
    if (roleEditData) {
      this.setState({roleEditData});
      this.setRoleModalVisible(true, true);
    } else {
      message.error("数据不存在");
    }
  }
  handleDeleteRole = (roleEditData) => {
    let thiz=this;
    if (roleEditData) {
      this.setState({roleEditData});
      let id = roleEditData.id;
      confirm({
        title: "温馨提示",
        content: "删除后不可恢复，是否确定删除？",
        onOk: () => {
          thiz.props.show();
          deleteRole(id).then((res) => {
            if (res.status.toLowerCase() === "success") {
              message.success(res.message || "删除成功");
            } else {
              message.error(res.message);
            }
            thiz.setRoleModalVisible(false);
            thiz.getRoleDataByGroup(thiz.state.groupSelectedRows[0].id,thiz.state.searchRoleValue);
          }).catch(e => {
          }).finally(() => {
            thiz.props.hide();
          })
        }
      });
    } else {
      message.error("数据不存在");
    }
  }
  handleConfigRole = () => {
    if (this.state.groupSelectedRows.length !== 0) {
      if (this.state.roleSelectedRows.length !== 0) {
        this.showConfigPage(true);
      } else {
        message.error("请选择一个功能角色");
        return false;
      }
    } else {
      message.error("请选择一个功能角色组");
      return false;
    }
  }
  //配置页面
  showConfigPage = (visible) => {
    this.setState({showConfigPage: visible});
  }

  handleShowPosition = (roleEditData) => {
    if (roleEditData) {
      this.setShowPositionVisible(true);
      this.setState({roleEditData});

    } else {
      message.error("数据不存在");
    }
  }
  handleShowUser = (roleEditData) => {
    if (roleEditData) {
      this.setShowUserVisible(true);
      this.setState({roleEditData});

    } else {
      message.error("数据不存在");
    }
  }
  handleGroupSave = () => {
    const saveData = this.groupFormRef.getFormValue();
    if (saveData) {
      this.setState({confirmLoading: true});
      saveFeatureRoleGroup(saveData).then((res) => {
        if(res&&res.status==="SUCCESS"){
          message.success(res.message || "保存成功");
          this.setGroupModalVisible(false);
          if(!this.state.isGroupEdit){//新增清空查询条件
            this.getDataSource("");
            this.setState({searchGroupValue:''})
          }else {
            this.getDataSource(this.state.searchGroupValue);
          }
        }else{
          message.error(res.message || "保存失败");
        }
      }).catch(e => {
      }).finally(() => {
        this.setState({confirmLoading: false});
      })
    }
  }
  handleRoleSave = () => {
    //表单数据同步
    if (this.roleFormRef && this.roleFormRef.props.form) {
      this.roleFormRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({ confirmLoading: true});
          if (!this.state.isRoleEdit) {
            delete values.id
          }
          if (cache && cache.get("Authorization") && cache.get("Authorization").tenantCode) {
            values.code = cache.get("Authorization").tenantCode + "-" + values.code
          }
          saveFeatureRole(values).then((res) => {
            if(res&&res.status==="SUCCESS"){
              message.success(res.message || "保存成功");
              this.setRoleModalVisible(false);
              if(!this.state.isRoleEdit){//新增清空查询条件
                this.getRoleDataByGroup(this.state.groupSelectedRows[0].id,"");
                this.setState({searchRoleValue:''})
              }else {
                this.getRoleDataByGroup(this.state.groupSelectedRows[0].id,this.state.searchRoleValue);
              }
            }else{
              message.error(res.message || "保存失败");
            }

          }).catch(e => {
          }).finally(() => {
            this.setState({confirmLoading: false});
          })

        }
      })
    }
    // const saveData = this.roleFormRef.getFormValue();
    // if (saveData) {
    //   saveFeatureRole(saveData).then((res) => {
    //     message.success(res.message || "保存成功");
    //     this.setRoleModalVisible(false);
    //     this.getRoleDataByGroup(this.state.groupSelectedRows[0].id);
    //   }).catch(e => {
    //   }).finally(() => {
    //     this.setState({confirmLoading: false});
    //   })
    // }
  }
  //选择行判断
  checkOnlyOneSelect = (isGroup = false) => {
    const {groupSelectedRows, roleSelectedRows} = this.state;
    let selectedRows = isGroup ? groupSelectedRows : roleSelectedRows;
    if (selectedRows.length === 0) {
      message.error('请选择一数据！');
      return false;
    }
    if (selectedRows.length > 1) {
      message.error('只能选择一行数据！');
      return false;
    }
    return true;
  };
  handleGroupRowSelect = (selectedRows) => {
    /*功能角色组切换后，要把角色选择情况，否则会记录之前的记录*/
    this.setState({groupSelectedRows: selectedRows,
      roleSelectedRows:[]});
    if (!selectedRows || selectedRows.length === 0) {
      this.setState({roleDataSource: []});
    } else {
      this.getRoleDataByGroup(selectedRows[0].id);
    }
  }
  handleRoleRowSelect = (selectedRows) => {
    this.setState({roleSelectedRows: selectedRows});
  }
  getRoleGroupColumns = () => {
    return [
      {
        title: "操作",
        width: 100,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className="row-operator" onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth
                operateCode="BASIC-QXGL-GNJSGL-EDITGROUP"
              >
                <a className="row-operator-item" onClick={() => this.handleEditGroup(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth
                operateCode="BASIC-QXGL-GNJSGL-DELETEGROUP"
              >
                <a className="row-operator-item" onClick={() => this.handleDeleteGroup(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: "代码",
        width: 100,
        dataIndex: "code"
      },
      {
        title: "名称",
        width: 200,
        dataIndex: "name"
      }
    ];
  }
  getRoleColumns = () => {
    return [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          let buttons = [
            <CheckAuth
              operateCode="BASIC-QXGL-GNJSGL-EDIT"
              key={index + "edit"}
            >
              <a className="row-operator-item" onClick={() => this.handleEditRole(record)}>编辑</a>
            </CheckAuth>,
            <CheckAuth
              operateCode="BASIC-QXGL-GNJSGL-DELETE"
              key={index + "delete"}
            >
              <a className="row-operator-item" onClick={() => this.handleDeleteRole(record)}>删除</a>
            </CheckAuth>,
            <CheckAuth
              operateCode="BASIC-QXGL-GNJSGL-VIEWPOSITION"
              key={index + "checkP"}
            >
              <a className="row-operator-item" onClick={() => this.handleShowPosition(record)}>查看岗位</a>
            </CheckAuth>,
            <CheckAuth
              operateCode="BASIC-QXGL-GNJSGL-VIEWUSERS"
              key={index + "checkU"}
            >
              <a className="row-operator-item" onClick={() => this.handleShowUser(record)}>查看用户</a>
            </CheckAuth>,
          ];
          return (
            <div className="row-operator" onClick={(e) => {
              e.stopPropagation()
            }}>
              <StandardDropdown
                operator={buttons}
              />
            </div>
          )
        }
      },
      {
        title: "代码",
        width: 150,
        dataIndex: "code"
      },
      {
        title: "名称",
        width: 200,
        dataIndex: "name"
      },
      {
        title: "角色类型",
        width: 100,
        dataIndex: "roleTypeRemark"
      },
      {
        title: "公共角色用户类型",
        width: 200,
        dataIndex: "userTypeRemark"
      }
    ];
  }
  groupSearchBtnCfg = () => {
    return {
      quickSearchCfg: {
        style: {width: 250},
        placeholder: "输入代码或名称查询",
        onSearch: (v) => {
          this.handleQuickSearchGroup(v)
        }
      }
    }
  }
  groupBtnsCfg = () => {
    return [
      {
        title: "新增",
        operateCode:"BASIC-QXGL-GNJSGL-ADDGROUP",
        propsCfg: {
          type: "primary",
          onClick: () => {
            this.handleAddGroup()
          }
        }
      }
    ]
  }
  roleSearchBtnCfg = () => {
    return {
      quickSearchCfg: {
        style: {width: 250},
        placeholder: "输入代码或名称查询",
        onSearch: (v) => {
          this.handleQuickSearchRole(v)
        }
      }
    }
  }
  roleBtnsCfg = () => {
    return [
      {
        title: "新增",
        operateCode:"BASIC-QXGL-GNJSGL-ADD",
        propsCfg: {
          type: "primary",
          onClick: () => {
            this.handleAddRole()
          }
        }
      },
      {
        title: "配置",
        operateCode:"BASIC-QXGL-GNJSGL-CONFIG",
        propsCfg: {
          onClick: () => {
            this.handleConfigRole()
          }
        }
      },
    ]
  }
  setGroupModalVisible = (groupVisible, isEdit = false) => {
    let newState = {groupVisible};
    if (groupVisible) {
      newState.isGroupEdit = isEdit;
    }
    this.setState(newState);
  }
  setRoleModalVisible = (roleVisible, isEdit = false) => {
    let newState = {roleVisible};
    if (roleVisible) {
      newState.isRoleEdit = isEdit;
    }
    this.setState(newState);
  }

  setShowUserVisible = (showUser) => {
    this.setState({showUser});
  }
  setShowPositionVisible = (showPosition) => {
    this.setState({showPosition});
  }
  getPositionColumns = () => {
    return [
      {
        title: "代码",
        dataIndex: "code",
        width: 90
      },
      {
        title: "名称",
        dataIndex: "name"
      },
      {
        title: "岗位类别",
        dataIndex: "positionCategory.name",
      },
      {
        title: "组织机构",
        dataIndex: "organization.namePath",
        width: 290
      }
    ];
  }
  getUserColumns = () => {
    return [
      {
        title: "用户名称",
        dataIndex: "userName",
        width: 200
      },
      {
        title: "用户类型",
        dataIndex: "userTypeRemark",
      }

    ];
  }
  getPathData = () => {
    const {showConfigPage, roleSelectedRows} = this.state;
    if (showConfigPage) {
      const path = [{name: `角色【${roleSelectedRows[0].name}】`}, {name: "配置"}];
      return [...this.initPath, ...path];
    } else {
      return this.initPath;
    }
  }
  getExtra = () => {
    const {showConfigPage} = this.state;
    if (showConfigPage) {
      return [
        <Button key={"return"} onClick={() => this.showConfigPage(false)}>返回</Button>
      ]
    }
    return null;
  }

  render() {
    const {
      roleGroupDataSource,
      roleDataSource,
      searchRoleValue,
      searchGroupValue,
      groupSelectedRows,
      roleSelectedRows,
      groupVisible,
      roleVisible,
      isGroupEdit,
      isRoleEdit,
      groupEditData,
      roleEditData,
      confirmLoading,
      showPosition,
      showUser,
      showConfigPage
    } = this.state;
    const roleTitle = isRoleEdit ? "编辑功能角色" : "新增功能角色";
    const groupTitle = isGroupEdit ? "编辑功能角色组" : "新增功能角色组";
    const positionTitle = "查看岗位";
    const userTitle = "查看用户";
    return (
      <HeadBreadcrumb
        pathData={showConfigPage ? this.getPathData() : null}
        rightExtra={this.getExtra()}
        className={"allocation-page"}
        style={showConfigPage ? {margin: 0, padding: 0, height: "100%",overflow: "hidden"} : {overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{height: "100%", display: showConfigPage ? "none" : "block"}}>
          <Col span={10} style={{height: "100%"}}>
            <DetailCard
              title="功能角色组"
              style={{height: "100%"}}
            >
              <ToolBar
                btnsCfg={this.groupBtnsCfg()}
                searchBtnCfg={this.groupSearchBtnCfg()}
              />
              <SimpleTable
                data={searchGroupValue ? roleGroupDataSource.filter(item=>item.tag):roleGroupDataSource}
                columns={this.getRoleGroupColumns()}
                rowsSelected={groupSelectedRows}
                onSelectRow={this.handleGroupRowSelect}
              />
            </DetailCard>
            {
              groupVisible && <EditRoleGroupModal
                title={groupTitle}
                confirmLoading={confirmLoading}
                visible={groupVisible}
                isEdit={isGroupEdit}
                editData={groupEditData}
                onRef={this.getGroupFormRef}
                onOk={this.handleGroupSave}
                onCancel={() => this.setGroupModalVisible(false)}
              />
            }
          </Col>
          <Col span={14}>
            <DetailCard
              className={"child-card"}
              title="功能角色"
              style={{height: "100%"}}
            >
              <ToolBar
                btnsCfg={this.roleBtnsCfg()}
                searchBtnCfg={this.roleSearchBtnCfg()}
              />
              <SimpleTable
                data={searchRoleValue ?roleDataSource.filter(item=>item.tag):roleDataSource}
                columns={this.getRoleColumns()}
                rowsSelected={roleSelectedRows}
                onSelectRow={this.handleRoleRowSelect}
              />
            </DetailCard>
            {
              roleVisible && <AddOrEditRoleModal
                title={roleTitle}
                confirmLoading={confirmLoading}
                modalVisible={roleVisible}
                isEdit={isRoleEdit}
                roleGroup={groupSelectedRows[0]?groupSelectedRows[0]:{}}
                defaultValue={isRoleEdit?roleEditData?roleEditData:{}:{}}
                // dataRoleGroup={this.state.roleSelectedRows[0] ? this.state.roleSelectedRows[0] : {}}
                onRef={this.getRoleFormRef}
                handleOk={this.handleRoleSave}
                handleCancel={() => this.setRoleModalVisible(false)}
              />
            }
            {
              showUser && <ModalBox
                title={userTitle}
                id={roleEditData.id}
                visible={showUser}
                onCancel={() => this.setShowUserVisible(false)}
                dataService={getUser}
                columns={this.getUserColumns()}
                quickSearchKey={["userTypeRemark", "userName"]}
              />
            }
            {
              showPosition && <ModalBox
                title={positionTitle}
                id={roleEditData.id}
                visible={showPosition}
                onCancel={() => this.setShowPositionVisible(false)}
                dataService={getPosition}
                columns={this.getPositionColumns()}
              />
            }
          </Col>
        </Row>
        {
          showConfigPage && <ShowConfigPage selectedRole={roleSelectedRows[0]}/>
        }
      </HeadBreadcrumb>
    );
  }
}

const mapStateToProps = (state) => {
  return {};
};
const mapDispatchToProps = {hide, show};
export default connect(mapStateToProps, mapDispatchToProps)(PageOperateHoc(FeatureRoleView));
